<template>
  <!-- 拆分模态框 -->
  <BasicModal
    @register="registerSplitModal"
    title="数据拆分"
    @ok="handleSplitConfirm"
    @visible-change="handleModalVisibleChange"
    width="500px"
  >
    <BasicForm @register="registerSplitForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, nextTick } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const { showMessage } = useMessage();

  // 定义组件的 props
  interface Props {
    // 可以根据需要添加其他 props
  }

  const props = withDefaults(defineProps<Props>(), {});

  // 定义组件的 emits
  const emit = defineEmits<{
    splitSuccess: [data: { originalRecord: any; newRecords: any[] }];
  }>();

  // 拆分模态框和表单
  const [registerSplitModal, { openModal: openSplitModal, closeModal: closeSplitModal }] = useModal();
  const currentSplitRecord = ref<Recordable>({});

  // 拆分表单配置
  const [registerSplitForm, { validate: validateSplit, setFieldsValue: setSplitFieldsValue, getFieldsValue: getSplitFieldsValue, resetFields: resetSplitFields }] = useForm({
    labelWidth: 100,
    schemas: [
      {
        label: '拆分个数',
        field: 'splitCount',
        component: 'InputNumber',
        defaultValue: 1,
        componentProps: {
          min: 1,
          max: 999,
          precision: 0,
          placeholder: '请输入拆分个数',
        },
        rules: [
          {
            required: true,
            message: '请输入拆分个数',
          },
        ],
      },
      {
        label: '拆分数量',
        field: 'splitQuantity',
        component: 'InputNumber',
        componentProps: {
          // min: 0.01,
          // precision: 2,
          placeholder: '请输入拆分数量',
        },
        rules: [
          {
            required: true,
            message: '请输入拆分数量',
          },
        ],
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });

  // 打开拆分模态框
  const openSplit = async (record: Recordable) => {
    console.log('openSplit', record);

    // 保存当前要拆分的记录
    currentSplitRecord.value = { ...record };

    // 打开拆分模态框（表单重置将在 handleModalVisibleChange 中处理）
    openSplitModal(true);

    console.log('当前拆分记录:', currentSplitRecord.value);
    console.log('当前数量:', currentSplitRecord.value.iqty);
  };

  // 检查表单是否准备就绪
  const isFormReady = () => {
    try {
      // 尝试调用表单方法，如果不抛出错误则表单已准备好
      getSplitFieldsValue();
      return true;
    } catch (error) {
      return false;
    }
  };

  // 等待表单准备就绪
  const waitForFormReady = async (maxRetries = 20, delay = 100) => {
    for (let i = 0; i < maxRetries; i++) {
      if (isFormReady()) {
        return; // 表单可用，退出循环
      }

      if (i === maxRetries - 1) {
        throw new Error('表单初始化超时');
      }

      // 等待一段时间后重试
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  };

  // 处理模态框可见性变化
  const handleModalVisibleChange = async (visible: boolean) => {
    if (visible) {
      console.log('模态框打开，开始初始化表单...');

      // 模态框打开时，等待表单渲染完成后重置表单
      await nextTick();

      try {
        // 等待表单准备就绪
        await waitForFormReady();

        // 重置表单字段
        resetSplitFields();

        console.log('表单初始化成功');
      } catch (error) {
        console.error('表单初始化失败:', error);
        showMessage('表单初始化失败，请重试', 'error');
      }
    } else {
      console.log('模态框关闭');
    }
  };

  // 处理拆分确认
  const handleSplitConfirm = async () => {
    try {
      // 检查表单是否准备就绪
      if (!isFormReady()) {
        showMessage('表单尚未准备就绪，请稍后重试', 'warning');
        return;
      }

      // 验证表单数据
      await validateSplit();
      
      // 获取表单数据
      const formValues = await getSplitFieldsValue();
      const { splitCount, splitQuantity } = formValues;
      
      console.log('拆分表单数据:', formValues);
      console.log('原始数量:', currentSplitRecord.value.iqty);
      
      // 验证拆分逻辑
      const originalQuantity = parseFloat(currentSplitRecord.value.iqty || 0);
      const totalSplitQuantity = splitCount * splitQuantity;
      
      if (totalSplitQuantity > originalQuantity) {
        showMessage('拆分数量不足，总拆分数量不能大于原始数量', 'error');
        return;
      }
      
      // 执行拆分逻辑
      const newRecords: any[] = [];
      
      // 生成指定个数的拆分记录
      const timestamp = Date.now();
      for (let i = 0; i < splitCount; i++) {
        // 创建完全独立的新记录，只保留必要的属性
        const newRecord = {
          // 基础属性
          id: `split_${timestamp}_${i + 1}`, // 生成完全独立的唯一ID
          iqty: splitQuantity,

          // 保留必要的业务属性（排除可能导致冲突的属性）
          basInv: currentSplitRecord.value.basInv ? { ...currentSplitRecord.value.basInv } : null,
          invCode: currentSplitRecord.value.invCode,
          invName: currentSplitRecord.value.invName,
          invSpec: currentSplitRecord.value.invSpec,
          unitCode: currentSplitRecord.value.unitCode,
          unitName: currentSplitRecord.value.unitName,
          price: currentSplitRecord.value.price,
          amt: currentSplitRecord.value.amt,

          // 添加拆分标记，便于识别
          isSplitRecord: true,
          originalRecordId: currentSplitRecord.value.id,
          splitIndex: i + 1,
          splitType: 'split',
          splitTimestamp: timestamp,
        };
        newRecords.push(newRecord);
      }

      // 如果有剩余数量，生成剩余记录
      const remainingQuantity = originalQuantity - totalSplitQuantity;
      if (remainingQuantity > 0) {
        // 创建完全独立的剩余记录
        const remainingRecord = {
          // 基础属性
          id: `remaining_${timestamp}`, // 生成完全独立的唯一ID
          iqty: remainingQuantity,

          // 保留必要的业务属性（排除可能导致冲突的属性）
          basInv: currentSplitRecord.value.basInv ? { ...currentSplitRecord.value.basInv } : null,
          invCode: currentSplitRecord.value.invCode,
          invName: currentSplitRecord.value.invName,
          invSpec: currentSplitRecord.value.invSpec,
          unitCode: currentSplitRecord.value.unitCode,
          unitName: currentSplitRecord.value.unitName,
          price: currentSplitRecord.value.price,
          amt: currentSplitRecord.value.amt,

          // 添加拆分标记，便于识别
          isSplitRecord: true,
          originalRecordId: currentSplitRecord.value.id,
          splitType: 'remaining',
          splitTimestamp: timestamp,
        };
        newRecords.push(remainingRecord);
      }
      
      console.log('生成的新记录:', newRecords);
      
      // 通过事件通知父组件
      emit('splitSuccess', {
        originalRecord: currentSplitRecord.value,
        newRecords: newRecords,
      });
      
      // 显示成功消息
      const message = remainingQuantity > 0 
        ? `拆分成功！生成了 ${splitCount} 条数量为 ${splitQuantity} 的记录和 1 条数量为 ${remainingQuantity} 的剩余记录`
        : `拆分成功！生成了 ${splitCount} 条数量为 ${splitQuantity} 的记录`;
      
      showMessage(message);
      
      // 关闭模态框
      closeSplitModal();
      
    } catch (error) {
      showMessage('表单验证失败，请检查输入', 'error');
      console.error('拆分失败:', error);
    }
  };

  // 暴露给父组件的方法
  defineExpose({
    openSplit,
  });
</script>

<style scoped>
  /* 可以根据需要添加样式 */
</style>
